package com.frasermccrossan.segue;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore.Audio.AudioColumns;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class PlayingScreen extends Activity implements OnClickListener, OnItemClickListener {

	public static final int ADD_DIALOG = 0; /* dialog created when first adding tracks */
	
	ImageButton mPlayButton;
	ImageButton mSkipButton;
	ImageButton mAddButton;
	ListView queueView;
	Cursor queueCursor = null;
	int curQueuePos = 0;
	int curQueuePosTop = 0;
	
	QueuePlayer mQueuePlayer = null;
	boolean mIsBound;
	TrackRepository repo;
	
	public class PlayingScreenCallback {
		public int foo;
	}
	
	PlayingScreenCallback callback = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.play_queue);
        mPlayButton = (ImageButton)findViewById(R.id.play_button);
        mSkipButton = (ImageButton)findViewById(R.id.skip_button);
        mAddButton = (ImageButton)findViewById(R.id.add_button);
        mPlayButton.setOnClickListener(this);
        mSkipButton.setOnClickListener(this);
        mAddButton.setOnClickListener(this);
        mAddButton.setEnabled(false);
    	// pass the button to be enabled on completion
        new GetRepoTask().execute(mAddButton);
        callback = new PlayingScreenCallback();
        queueView = (ListView)findViewById(R.id.track_list);
        queueView.setOnItemClickListener(this);
        queueView.setEnabled(false);
        startService(new Intent(this, QueuePlayer.class));
    }

    private class GetRepoTask extends AsyncTask<View, Void, View> {

	    protected View doInBackground(View... v) {
	    	Segue segue = (Segue)getApplication();
	    	repo = segue.getRepo(PlayingScreen.this);
	    	return v[0];
	    }
	    
	    protected void onPostExecute(View v) {
	        v.setEnabled(true);
	    }
	    
	}

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mQueuePlayer = ((QueuePlayer.QueueBinder)service).getService();
            mQueuePlayer.setCallback(callback);
        }

        public void onServiceDisconnected(ComponentName className) {
        	clearQueueViewAdapter();
            mQueuePlayer = null;
        }
    };

    private void clearQueueViewAdapter() {
    	if (queueCursor != null) {
    		queueCursor.close();
    		queueCursor = null;
    	}
    	CharSequence[] dummyArray = {};
    	queueView.setAdapter(new ArrayAdapter<CharSequence>(this,
    			android.R.layout.simple_list_item_1,
    			dummyArray));
    }

    private void setQueueViewAdapter(boolean restorePos) {
    	int curPos = 0;
    	View v;
    	int top = 0;
    	if (restorePos) {
    		curPos = queueView.getFirstVisiblePosition();
    		v = queueView.getChildAt(0);
    		top = (v == null) ? 0 : v.getTop();
    	}
    	if (queueCursor != null) {
    		queueCursor.close();
    	}
    	queueCursor = mQueuePlayer.getQueueCursor();
    	queueView.setAdapter(new SimpleCursorAdapter(getApplicationContext(),
    			android.R.layout.two_line_list_item,
    			queueCursor,
    			new String[] { AudioColumns.TITLE, AudioColumns.ARTIST },
    			new int[] { android.R.id.text1, android.R.id.text2 }));
    	if (restorePos) {
    		queueView.setSelectionFromTop(curPos, top);
    	}
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	mIsBound = bindService(new Intent(this, QueuePlayer.class), mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onResume() {
    	setQueueViewAdapter(true);
        queueView.setEnabled(true);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.playing_screen_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.prefs:
            gotoPreferences();
            return true;
        case R.id.exit:
        	stopService(new Intent(this, QueuePlayer.class));
        	finish();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	@Override
    public void onClick(View clicked) {
    	if (clicked == mPlayButton) {
    		mQueuePlayer.playToggle();
    	}
    	else if (clicked == mSkipButton) {
    		mQueuePlayer.proclaim("Skip clicked");
    	}
    	else if (clicked == mAddButton) {
    		startActivity(new Intent(PlayingScreen.this, BrowseLibrary.class));
    	}
    	else {
    		mQueuePlayer.proclaim("Fucked up!");
    	}
    }

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (parent == queueView) {
			mQueuePlayer.delTrack(position);
		}
	}

    void gotoPreferences() {
    	Intent prefs = new Intent(PlayingScreen.this, MainPreferences.class);
    	startActivity(prefs);
    }
    
    @Override
    protected void onPause() {
    	queueView.setEnabled(false);
    }
    
    @Override
    protected void onStop() {
    	mQueuePlayer.setCallback(null);
        if (mIsBound) {
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
        }
    	super.onStop();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}